package com.tools.utils;

import com.tools.constants.Constant;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;

import java.io.File;
import java.io.IOException;

import static org.eclipse.jgit.api.Git.cloneRepository;

/**
 * GitUtil
 *
 * @author < a href=" ">ZhangYang</ a>
 * @version v1.0.01
 * @date 2018-08-22 10:49
 */
public class GitUtil {
  public static String localRepoPath = "./template";
  public static String localRepoGitConfig = "./template/.git";
  public static String remoteRepoURI = "http://zhangyang@local-git:10101/r/tools-template.git";
  public static String localCodeDir = "D:/platplat";

  public static void commitFiles() throws IOException, GitAPIException {
    String filePath = "";
    Git git = Git.open(new File(localRepoGitConfig));
    //创建用户文件的过程
    File myfile = new File(filePath);
    myfile.createNewFile();
    git.add().addFilepattern("pets").call();
    //提交
    git.commit().setMessage("Added pets").call();
    //推送到远程
    git.push().call();
  }

  public static boolean pullBranchToLocal(String cloneURL) {
    boolean resultFlag = false;
    String[] splitURL = cloneURL.split(" ");
    String branchName = splitURL[1];
    String fileDir = localCodeDir + "/" + branchName;
    //检查目标文件夹是否存在
    File file = new File(fileDir);
    if (file.exists()) {
      deleteFolder(file);
    }
    Git git;
    try {
      git = Git.open(new File(localRepoGitConfig));
      cloneRepository().setURI(cloneURL).setDirectory(file).call();
      resultFlag = true;
    } catch (IOException e) {
      e.printStackTrace();
    } catch (GitAPIException e) {
      e.printStackTrace();
    }
    return resultFlag;
  }

  public static void deleteFolder(File file) {
    if (file.isFile() || file.list().length == 0) {
      file.delete();
    } else {
      File[] files = file.listFiles();
      for (int i = 0; i < files.length; i++) {
        deleteFolder(files[i]);
        files[i].delete();
      }
    }
  }

  public static void setupRepo() throws GitAPIException {
    //建立与远程仓库的联系，仅需要执行一次
    Git git = cloneRepository().setURI(remoteRepoURI).setDirectory(new File("./"+Constant.TEMPLATE_DIR_NAME)).call();
  }

  public static void main(String[] args) throws GitAPIException {
    setupRepo();
  }
}
